package com.xfcycle.zebrabikegp.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.constant.BluetoothDeviceConstant;
import com.xfcycle.zebrabikegp.constant.SpConstant;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.dto.InstructionRecordDTO;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;
import com.xfcycle.zebrabikegp.util.HandleDataBySharePreferencesUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 车辆固件信息
 * Created by Feng Jiantao on 2018/3/6.
 */

public class BikeInfoActivity extends RootActivity {
    private static final String TAG = "BikeInfoActivity";

    private ImageView iv_back;
    private ListView lv_bike_info;
    private RelativeLayout rl_cover;

    private List<InstructionRecordDTO> instructionRecordDTOList;
    private List<Map<String, String>> instructionsData;
    private SimpleAdapter instructionsAdapter;

    //蓝牙连接工具类
    private HandleDataByBLEUtil handleDataByBLEUtil;
    //蓝牙广播接收类
    private HomeMapHandleDataFromBleReceiver homeMapHandleDataFromBleReceiver;

    private String currentInstruction;
    private String currentInstructionExplain;

    private String[] instructionList = {"AT+IMEI", "AT+ICCID", "AT+SPI", "AT+VER1", "AT+VER2", "AT+VER3"};

    private String[] instructionExplainList = {"GSM IMEI", "SIM ICCID", "SPI ID", "BLE VER", "GSM VER", "ASI VER"};

    private Integer instructionIndex = 0;

    private String resultTemp = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bike_info);

        initView();
        initViewListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //注册接收蓝牙数据
        registBroadcastReceiverAtActivity(homeMapHandleDataFromBleReceiver, BluetoothDeviceConstant.GET_DATA_FROM_BLUETOOTH_BROADCAST_RECEIVER_ACTION);

        //更新数据
        initViewContent();
    }

    @Override
    protected void onPause() {
        super.onPause();

        //注销广播
        if (null != homeMapHandleDataFromBleReceiver) {
            unregisterReceiver(homeMapHandleDataFromBleReceiver);
        }
    }
    /***********************************************************************************************/
    /**                                     自定义私有方法                                         **/
    /***********************************************************************************************/
    private void initView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        lv_bike_info = (ListView) findViewById(R.id.lv_bike_info);
        rl_cover = (RelativeLayout) findViewById(R.id.rl_cover);

        handleDataByBLEUtil = HandleDataByBLEUtil.getInstance(this, 20 * 1000);
        homeMapHandleDataFromBleReceiver = new HomeMapHandleDataFromBleReceiver();

        instructionRecordDTOList = new ArrayList<>();
        instructionsData = new ArrayList<>();

        //Adapter 绑定数据源
        instructionsAdapter = new SimpleAdapter(this, instructionsData, R.layout.item_bike_info, new String[]{"instruction", "result"}, new int[]{R.id.tv_history_record_instruction, R.id.tv_history_record_result});
        lv_bike_info.setAdapter(instructionsAdapter);
    }

    private void initViewListener() {
        //返回上一层
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });
    }

    private void initViewContent() {
        if (!BlueToothAssist.isConnect) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.DEVICE_DISCONNECT, Toast.LENGTH_LONG).show();
            return;
        }

        if (!BlueToothAssist.isUnlock) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.BIKE_LOCKED, Toast.LENGTH_LONG).show();
            return;
        }

        rl_cover.setVisibility(View.VISIBLE);

        String bikeName = HandleDataBySharePreferencesUtil.getInstance(this).getDateFromSharePre(SpConstant.SP_NAME, SpConstant.HISTORY_CONNECT_BIKE_NAME_KEY);
        //展示车辆名称
        showInstructionResult("BLE NAME", bikeName);

        instructionIndex = 0;

        currentInstruction = instructionList[instructionIndex];
        currentInstructionExplain = instructionExplainList[instructionIndex];

        //发送第一条查询指令
        sendTestInstruction(currentInstruction);
    }

    //发布查询指令
    private void sendTestInstruction(String instruction) {
        if (null == instruction || "".equals(instruction)) {
            return;
        }

        SystemClock.sleep(500);

        handleDataByBLEUtil.sendDataToDevice(instruction);
    }

    //展示测试指令结果集
    private void showInstructionResult(String instructionDesc, String result) {

        if (null == instructionDesc || "".equals(instructionDesc) || null == result || "".equals(result)) {
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("instruction", instructionDesc);
        map.put("result", result);
        instructionsData.add(map);

        instructionsAdapter.notifyDataSetChanged();
    }

    /***********************************************************************************************/
    /**                                       自定义广播接收者类                                    **/
    /***********************************************************************************************/
    /**
     * 广播接收者类，负责接收从蓝牙发出的数据并对其进行处理
     */
    class HomeMapHandleDataFromBleReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String result = intent.getStringExtra("result");

            //对从蓝牙获取到的数据进行处理
            Log.i(TAG, "onReceive: --- 接收到的结果 --- " + result);

            if (null != result) {

                if (result.contains("IMEI") || result.contains("ICCID") || result.contains("GACC") || result.contains("GSM")) {
                    resultTemp = result;
                    return;
                }

                //展示当前指令
                showInstructionResult(currentInstructionExplain, resultTemp + result);

                resultTemp = "";

                if (instructionIndex < instructionList.length - 1) {
                    instructionIndex++;

                    currentInstruction = instructionList[instructionIndex];
                    currentInstructionExplain = instructionExplainList[instructionIndex];

                    //发送下一条指令
                    sendTestInstruction(currentInstruction);


                } else {
                    //隐藏等待框
                    rl_cover.setVisibility(View.GONE);
                }
                return;
            }
        }
    }
}
